package com.i2works.smartluolong.api.controller.common;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.i2works.smartluolong.utils.base.AppConstant;
import com.i2works.smartluolong.utils.base.MsgEnum;
import com.i2works.smartluolong.utils.base.ShiroConstants;
import com.i2works.smartluolong.utils.common.HmacUtil;
import com.i2works.smartluolong.utils.common.SmsUtil;
import com.i2works.smartluolong.utils.entity.R;
import com.i2works.smartluolong.utils.entity.Result;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 短信
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2018/1/29 16:52
 */
@RestController
@RequestMapping("/common/sms")
public class SmsController {

    private final SmsUtil smsUtil;

    @Autowired
    public SmsController(SmsUtil smsUtil) {
        this.smsUtil = smsUtil;
    }

    /**
     * 发送短信
     *
     * @param phone  手机号码
     * @param date   时间戳
     * @param digest 摘要
     */
    @PostMapping("/send")
    public Result send(
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "date", required = false) String date,
            @RequestParam(value = ShiroConstants.APP_DIGEST, required = false) String digest) {
        //参数判断
        if (StringUtils.isAnyBlank(digest, phone, date) && !NumberUtils.isDigits(date) && !NumberUtils.isDigits(phone)) {
            return R.error(MsgEnum.ATTRS_ERROR.getMsg());
        }
        //参数列表
        Map<String, Object> params = Maps.newLinkedHashMap();
        params.put("phone", phone);
        params.put("date", date);
        String serviceDigest = HmacUtil.digest(HmacUtil.getKey(phone), params);
        if (StringUtils.equalsIgnoreCase(digest, serviceDigest) && differ(Long.parseLong(date))) {
            return smsUtil.captcha(AppConstant.ALIYUN_SMS_TEMPLATECODE, Lists.newArrayList(phone));
        } else {
            return R.error(MsgEnum.ACCESS_AUTHC_FAIL.getMsg());
        }
    }

    /**
     * 校验短信
     */
    @PostMapping("/check")
    public Result check(@RequestParam(value = "code", required = false) String code, @RequestParam(value = "phone", required = false) String phone) {
        return smsUtil.contrast(phone, code);
    }

    /**
     * 验证鉴权时间的时间差
     *
     * @see 客户端发送的时间 与  当前系统时间 进行对比
     * @see 两者相差 <=300秒，否则鉴权失败
     */
    private boolean differ(Long date) {
        return ((System.currentTimeMillis() - date) / 1000) <= ShiroConstants.APP_EXP_TIME;
    }


}
